const mongoose = require('mongoose');
const Joi = require('joi');
const bcrypt = require('bcrypt');

const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 20
    },
    email: {
        type: String,
        // 保证邮箱地址唯一
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    role: {
        type: String,
        // admin: 超级管理员  normal: 普通用户
        enum: ['admin', 'normal'],
        required: true
    },
    state: {
        type: Number,
        default: 0 // 启用、禁用状态
    }
});

const User = mongoose.model('User', userSchema);


// async function createUser(user_info){
//     const salt = await bcrypt.genSalt(10);
//     user_info.password = await bcrypt.hash(user_info.password, salt);

//     const user = await User.create(user_info)
//     .then(() => console.log("用户创建成功"))
//     .catch(() => console.log("用户创建失败"));
// }


// createUser({
//     username: "ionluo",
//     email: "ionluo@cyagen.com",
//     password: "123456",
//     role: 'admin',
//     state: 1
// });


const validateUser = userInfo => {
    // 定义对象的验证规则
    // 注意这里不设置required的话，参数是可选的
    const schema = {
        username: Joi.string().min(2).max(12).error(new Error("用户名应该为2-12个字符")),
        email: Joi.string().email().required().error(new Error("邮箱地址不正确")),
        password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/).required().error(new Error("密码必须是3-30位的普通字符")),
        role: Joi.string().valid('normal', 'admin').required().error(new Error("角色必须是normal或者admin")),
        state:Joi.number().valid(0, 1).required().error(new Error("状态必须是0或者1"))
    }

    // npm install joi@14.3.1
    // 这里版本过高报错  Joi.validate is a not function
    // 返回验证结果的Promise对象
    return Joi.validate(userInfo, schema);
}

module.exports = {
    User,
    validateUser
}